﻿/**
* 本文件用于调用geoserver切割的瓦片
* @author Wilson.Yan
* @version 2016.8.21
*/
//改变数字格式
function TileMongodbService(layerInfo) {
    var geoTiles = new Object;
    geoTiles.id = layerInfo.GUID;
    geoTiles.name = layerInfo.NAME;
    geoTiles.url = layerInfo.URL;
    geoTiles.wkid = layerInfo.hasOwnProperty("WKID")?layerInfo.WKID:"3857";
    geoTiles.bbox = layerInfo.BBOX;
    geoTiles.miniresolution = layerInfo.hasOwnProperty("MINIRESOLUTION")?layerInfo.MINIRESOLUTION:0;
    geoTiles.maxresolution = layerInfo.hasOwnProperty("MAXRESOLUTION")?layerInfo.MAXRESOLUTION:19;
    geoTiles.minzoom = layerInfo.hasOwnProperty("MINZOOM") ? layerInfo.MINZOOM : 0;
    geoTiles.maxzoom = layerInfo.hasOwnProperty("MAXZOOM") ? layerInfo.MAXZOOM : 19;
    geoTiles.prj = layerInfo.PRJ;
    geoTiles.CreateLayer = function () {
        //gridset分辨率，geoserver内查看
        //var resolutions = this.resolutions;// [156543.03392804097, 78271.51696402048, 39135.75848201024, 19567.87924100512, 9783.93962050256, 4891.96981025128, 2445.98490512564];
        var name = this.name;
        var url = this.url + "&t=" + name; // '/data/map_worldmap/{z}/{f}/{x}_{y}.png'; //初步的url
        var wkid = this.wkid;
        var id = this.id;
        var bbox = this.bbox;

        var minzoom = this.minzoom;
        var maxzoom = this.maxzoom;
        if (minzoom == "" || minzoom == null || minzoom == "undefind") {
            minzoom = 1;
        }
        if (maxzoom == "" || maxzoom == null || maxzoom == "undefind") {
            maxzoom = 19;
        }
        var minResolution = this.miniresolution;
        var maxResolution = this.maxresolution;
        var mapProj = this.prj; // "EPSG:" + wkid;
        var extent = ol.proj.get(mapProj).getExtent();
        var resolutions = getResolution(mapProj, minResolution, maxResolution);
        //定义数据源
        var fileDel = calFileNum(minzoom, maxzoom);
        var source = new ol.source.TileImage({
            projection: ol.proj.get(mapProj),
            tileSize: 256,
            cacheSize: 40960,
            maxZoom: maxzoom,
            minZoom: minzoom,
            /*		urls:getUrls(z,extent,resolutions),*/
            tileGrid: new ol.tilegrid.TileGrid({
                //origin: ol.extent.getBottomLeft(extent), //
                origin: ol.extent.getTopLeft(extent), //
                resolutions: resolutions, //
                tileSize: [256, 256],
                extent: bbox
            }),

            tileUrlFunction: function (tileCoord) {

                //#region 重写服务请求地址，重新计算行列号

                var z = Math.abs(tileCoord[0]);
                var sum = Math.pow(2, z);
                var x = tileCoord[1];
                var y = tileCoord[2] + sum;
                var tempFile = Math.sqrt(fileDel[z]); //边数
                var tryx = Math.ceil((x + 1) / tempFile) - 1; //x所在列（关键点）
                var tryy = Math.ceil((y + 1) / tempFile) - 1; //y所在行（关键点）
                var parm_z = "EPSG_" + wkid + "_" + PrefixInteger(z, 2);
                var parm_file = "";
                var parm_x = "";
                var parm_y = "";
                if (z < 6) {
                    parm_file = tryx.toString() + '_' + tryy.toString();
                    parm_x = PrefixInteger(x, 2);
                    parm_y = PrefixInteger(y, 2);
                }
                else if (z < 12) {
                    parm_file = PrefixInteger(tryx, 2) + '_' + PrefixInteger(tryy, 2);
                    parm_x = PrefixInteger(x, 4);
                    parm_y = PrefixInteger(y, 4);
                }
                else if (z < 18) {
                    parm_file = PrefixInteger(tryx, 3) + '_' + PrefixInteger(tryy, 3);
                    parm_x = PrefixInteger(x, 6);
                    parm_y = PrefixInteger(y, 6);
                }
                else {
                    parm_file = PrefixInteger(tryx, 4) + '_' + PrefixInteger(tryy, 4);
                    parm_x = PrefixInteger(x, 8);
                    parm_y = PrefixInteger(y, 8);
                }
                var ss = "";
                if (url.indexOf("aspx") != -1)
                    ss = url.replace('{z}', z).replace('{x}', x).replace('{y}', y);
                else
                    ss = url.replace('{z}', parm_z).replace('{f}', parm_file).replace('{x}', parm_x).replace('{y}', parm_y);
                return ss;

                //#endregion
            },
            wrapX: false
        });
        source.set("id", id, true);
        //创建离线瓦片图层
        var LocalLayer = new ol.layer.Tile({
            extent: extent,
            source: source,
            name: name,
            proxy: new Cesium.DefaultProxy('/proxy/'),
            minResolution: resolutions[maxzoom],
            maxResolution: resolutions[minzoom]
        });
        return LocalLayer;
        //根据地图投影，最大最小等级获取切片规则
        function getResolution(mapProj, minLevel, maxLevel) {
            var projExtent = ol.proj.get(mapProj).getExtent();
            var startResolution = ol.extent.getWidth(projExtent) / 256;
            var resolutions = new Array(maxLevel);
            for (var i = 0; i < maxLevel; ++i) {
                //if(i>=minLevel)
                resolutions[i] = startResolution / Math.pow(2, i);
            }
            return resolutions;
        }
    };
    return geoTiles;
}

function fix(str, length) {
    var temp = "00" + str.toString();
    return temp.substr(temp.length - 2, length);
}
function PrefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}

//--------计算文件数方法-------------//
function calFileNum(minZoom, maxZoom) {
    var fileDelta = new Array(maxZoom - minZoom + 1); //每个文件夹的边数组
    for (var i = 0; i <= maxZoom; i++) {
        if (i % 2 == 0) { //偶数
            fileDelta[i] = Math.pow(2, i + 2);
        }
        else { //奇数
            fileDelta[i] = fileDelta[i - 1];
        }
    }
    return fileDelta;
}